package com.qianbei.user.regist;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;

import com.android.volley.Request.Method;
import com.qianbei.R;
import com.qianbei.common.base.BaseFragment;
import com.qianbei.common.init.GlobalConfig;
import com.qianbei.common.init.SetData;
import com.qianbei.common.net.control.ServerControl;
import com.qianbei.common.net.control.ServerControl.ServerListener;
import com.qianbei.common.net.control.ServerResult;
import com.qianbei.common.net.view.MsgAlert;
import com.qianbei.common.net.view.ProgressDialog;
import com.qianbei.common.util.ConstantValue;
import com.qianbei.common.utilis.IDCard;
import com.qianbei.common.utilis.Util;
import com.qianbei.common.web.WebActivity;
import com.qianbei.user.login.CountryCodeActivity;
import com.qianbei.user.model.UserMode;

public class RegisterFragment extends BaseFragment {
	private EditText et_mobile, et_identifyingCode, et_password, et_name;
	private TextView tv_identifyingCode,mAgreementTv;
	private String str_mobile, str_identifyingCode, str_password, name;

	private TextView mCountryNumberTv;

	private String mCountryCode="86";
	private String mCountryName="中国";

	@Override
	public View onCreateView(LayoutInflater inflater,
			@Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
		View v = View.inflate(mContext, R.layout.user_register, null);
		initWidget(v);
		return v;
	}

	private void initWidget(View v) {
		et_mobile = (EditText) v.findViewById(R.id.et_mobile);
		et_name = (EditText) v.findViewById(R.id.et_name);
		et_identifyingCode = (EditText) v.findViewById(R.id.et_identifyingCode);
		et_password = (EditText) v.findViewById(R.id.et_password);
		mCountryNumberTv = (TextView) v.findViewById(R.id.tv_country_number);

		mAgreementTv = (TextView) v.findViewById(R.id.tv_agreement);
		tv_identifyingCode = (TextView) v.findViewById(R.id.register_getcode);
		tv_identifyingCode.setOnClickListener(this);
		v.findViewById(R.id.btn_register).setOnClickListener(this);

		mAgreementTv.setOnClickListener(this);
		mCountryNumberTv.setOnClickListener(this);
	}


	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		super.onClick(v);
		switch (v.getId()) {
		case R.id.register_getcode:
			String msg = checkUserInputValues(true);
			// String msg = "0";
			if (!"0".equals(msg)) {
				new MsgAlert().show(msg);
				return;
			} else {
				// 获取注册验证码
				registerCheck(str_mobile, "1");
				hideSoftInputFromWindow();
			}

		
			break;

		case R.id.btn_register:

			String msg1 = checkUserInputValues(false);
			if (!"0".equals(msg1)) {
				new MsgAlert().show(msg1);
				return;
			} else {
				Register(str_mobile, str_identifyingCode, str_password);
				Util.hideSoftInputFromWindow(v);

			}
			break;

		case R.id.tv_agreement:
			WebActivity.startWebActivity(getActivity(),  REGIEST_AGREEMENT_URL);
			break;
		case R.id.tv_country_number:
			startActivityForResult(new Intent(getActivity(), CountryCodeActivity.class),1);
			break;
		default:
			break;
		}
	}

	Handler handler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case 22:
				tv_identifyingCode.setText(msg.arg1 + "秒后重新获取");

				if (msg.arg1 == 0) {
					tv_identifyingCode.setClickable(true);
					tv_identifyingCode.setText(R.string.menu_register_tv_identifyingCode);
				} else {
					Message msgs = new Message();
					msgs.arg1 = msg.arg1 - 1;
					msgs.what = 22;
					handler.sendMessageDelayed(msgs, 1000);
				}

				break;

			default:
				break;
			}

		}
	};

	/**
	 * 1:注册、2:忘记密码、3:更换手机号
	 * 
	 */
	private void registerCheck(String phone_number, String type) {
		ServerControl sc = new ServerControl(URL_USER + "get_sms_code",
				"country_code",mCountryCode,
				"phone_number", phone_number,
				"type", type);
		sc.serverListener = new ServerListener() {

			@Override
			public void serverFinish(ServerResult sr) {
				if (sr.isContinue) {
					new MsgAlert().show(sr.bodyData.optString("msg"));
					Message msgs = new Message();
					msgs.arg1 = 60;
					msgs.what = 22;
					handler.sendMessageDelayed(msgs, 1000);
					tv_identifyingCode.setClickable(false);

				}
			}
		};
		new ProgressDialog(mContext).startControl(sc, "获取验证码");
	}

	/**
	 * 注册接口
	 * 
	 * @param phone
	 * @param code
	 * @param password
	 */
	private void Register(final String phone, String code,
			final String password) {
		ServerControl sc = new ServerControl(Method.POST, Regist,
				"phone_number", phone,
				"captcha", code,
				"password", password,
				"country_code",mCountryCode
		);
		sc.serverListener = new ServerListener() {

			@Override
			public void serverFinish(ServerResult sr) {
				if (sr.isContinue) {
					UserMode mode = new UserMode();
					mode.user_id = sr.bodyData.optString("user_id");
					mode.easemob_name = sr.bodyData.optString("easemob_name");
					mode.random_string = sr.bodyData.optString("random_string");
					saveRegisterInfo(mode);

					mContext.startActivity(new Intent(mContext,
							ImproveDataActivity.class));


				}
			}
		};
		new ProgressDialog(mContext).startControl(sc, "正在注册");

	}

	private String checkUserInputValues(boolean isGetRegCode) // 手机号与密码的格式
	{

		name = et_name.getText().toString().trim();

//		if (TextUtils.isEmpty(name)) {
//			return "昵称不能为空";
//		}

		str_mobile = et_mobile.getText().toString().trim();
		/** 电话号码验证 */
		if (TextUtils.isEmpty(str_mobile)) {
			return getString(R.string.menu_login_activity_check_mobile_null);
		}
		if ("86".equals(mCountryCode) && str_mobile.length() != 11) {
			return getString(R.string.menu_login_activity_check_mobile_length);
		}
		if ("86".equals(mCountryCode) && !IDCard.isMobileNO(str_mobile)) {
			return getString(R.string.menu_login_activity_check_mobile_format);
		}
		if (isGetRegCode) {
			return "0";
		}

		str_identifyingCode = et_identifyingCode.getText().toString().trim();;
		if (TextUtils.isEmpty(str_identifyingCode)) {
			return "验证码不能为空";
		}
		str_password = et_password.getText().toString().trim();;
		if (TextUtils.isEmpty(str_password)) {
			return getString(R.string.menu_login_activity_check_password);
		}
		if (str_password.length() < 8 || str_password.length() >16) {
			return getString(R.string.menu_register_activity_check_password_length_min);
		}
		String regex = "[A-Za-z0-9]+";
		if (!str_password.matches(regex)) {
			return getString(R.string.menu_register_activity_check_password_regex);
		}

		return "0";
	}

	private void saveRegisterInfo(UserMode mode) {
		// SharedPreferences userInfo =
		// mContext.getSharedPreferences("user_info",
		// 0);
		// userInfo.edit().putString("userIdentifyingCode", id).commit();
		SetData.setUserID(mode.user_id);
		SetData.setFace(mode.profile_image_url);
		SetData.sethxID(mode.easemob_name);
		SetData.sethxpass(mode.random_string);
		SetData.setUserPhone(str_mobile);

	
//		JpushManager.getIJpushManager().setAlias(mode.easemob_name);
//		JpushManager.getIJpushManager().setTag("jiemianmaster_register_user");

//		if (mode.type!=nullmode.type.equals("true")) {// true 是前辈
//			GlobalConfig.getInstance().identity = "1";
//			SetData.setIdentity("1");
//		} else {
			SetData.setIdentity("0");
			GlobalConfig.getInstance().identity = "0";
//		}
//		HuanxinHelper.getInstance().login();

	}


	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);

		if (mContext.RESULT_OK == resultCode && data != null){
			mCountryCode = data.getStringExtra(ConstantValue.COUNTRY_CODE_KEY);
			mCountryName = data.getStringExtra(ConstantValue.COUNTRY_NAME_KEY);
			mCountryNumberTv.setText(getString(R.string.country_code_format,mCountryName,mCountryCode));
		}
	}
}